/**
 * Created by youliangcheng on 17/6/22.
 */

//********************************** 以下为公共方法**********************************
function isBlack(str) {
    var isBlack = 0 ;
    if(str==null || str == '' || str == undefined){
        isBlack = 1 ;
    }
    return isBlack ;
}

//初始化图片,
function initImg(src) {
    console.log(src)
    $("#img_src").attr("src",src);
    $('#img_src_hidden').val(src);
    var img_tmp = $("#img_tmp").clone();
    var img_htm = img_tmp.html();
    // img_htm = img_htm.replaceAll("imgSrc", src + "?x-oss-process=image/resize,m_fill,h_800,w_800");
    var $li = img_tmp.html(img_htm).find("li");
    $("#addli").before($li);
    var imgLi = $("#addli").prev("li");
    imgLi.find("a").bind("click",function(){
        $(this).parent().remove();
        if ($(".imgs").length >= 2) {
            $("#addli").hide();
        } else {
            $("#addli").show();
        }
    })
    img_tmp.remove();
}
//初始化图片,
function initImg2(src) {
    console.log("src2"+src)
    $("#img_src2").attr("src",src);
    $('#img_src_hidden2').val(src);
    var img_tmp2 = $("#img_tmp2").clone();
    var img_htm = img_tmp2.html();
    // img_htm = img_htm.replaceAll("imgSrc", src + "?x-oss-process=image/resize,m_fill,h_800,w_800");
    var $li = img_tmp2.html(img_htm).find("li");
    $("#addli2").before($li);
    var imgLi = $("#addli2").prev("li");
    imgLi.find("a").bind("click",function(){
        $(this).parent().remove();
        if ($(".imgs2").length >= 2) {
            $("#addli2").hide();
        } else {
            $("#addli2").show();
        }
    })
    img_tmp2.remove();
}

//********************************** 以下是product的js方法**********************************
 function getProductList(typeId , type_index) {
     $('.type_id').removeClass('active');
     $('#typeId_'+type_index).addClass('active');

     $.getJSON('/product/loadList', {typeId: typeId}, function (data) {
         console.log(data);
         var gettpl = document.getElementById('product_list_tpl').innerHTML;
         laytpl(gettpl).render(data, function (html) {
             document.getElementById('productList').innerHTML = html;
             $("#productList").scrollTop(0);
         });
     })
 }

//修改
function modifiy(id) {
    // $.toast(id);
    var url = '/product/detail/'+id;
    $.router.load(url,true);
}
//删除
function delProduct(id) {
   
    $(document).on('click','.deleted-ok', function () {
        $.confirm('您确认要删除?', function () {
            $.getJSON('/product/delete',{id:id},function (data) {
                if(data.success){
                    $.toast('删除成功!');
                    var url = '/product/list';
                    if(data.typeId != null)
                        url += '/' + data.typeId;
                    // $.router.load(url);
                    window.location.href = url;
                }else {
                    $.toast(data.msg);
                }
            })
        });
    });


   
}


//保存产品
function savePro() {
    var id = $('#id_productId').val();
    var name = $('#id_name').val();
    console.log(name);
   var typeId = $('#id_typeId').val();
    var parentTypeId = $('#parentTypeId').val();
    var spec = $('#id_spec').val();
    var unit = $('#id_unit').val();
    var merchantPrice = $('#id_merchantPrice').val();
    var pcContent = $('#id_pcContent').val();
    var productSatus = $('#id_productStatus').val();
    var oldPrice = $('#id_oldPrice').val();

    var stock = $('#id_stock').val();

    if(name == null || name == ''){
        $.toast('请填写商品名!!');
        return;
    }
    if(name.length >= 10){
        $.toast('商品名不能超过10字!!');
        return;
    }
    if(parentTypeId == null || parentTypeId == 0 ){

        $.toast('请选择商品大类!');
        return;
    }
    if(typeId == null || typeId == 0 ){

        $.toast('请选择商品小类!');
        return;
    }
    if(spec == null || spec == ''){
        $.toast('请填写商品规格!');
        return;
    }
    if(unit == null || unit == ''){
        $.toast('请填写单位!');
        return;
    }
    if(merchantPrice == null || merchantPrice <= 0){
        $.toast('请填写正确价格!');
        return;
    }
    if(stock == null || stock == ''){
        $.toast('请设置库存!');
        return;
    }
    if(productSatus == null || productSatus == ''){
        $.toast('请选择上架状态!');
        return;
    }

    if(pcContent == null || pcContent == ''){
        $.toast('请描述商品!');
        return;
    }
    if(oldPrice == null || oldPrice == ''){
        $.toast('请填写原价!');
        return;
    }

    var mainImage = '';

    $(".imgs_1").each(function (i) {
        if (i == $(".imgs_1").length - 1) {
            return;
        }
        if ($(this).val() != undefined && $(this).val() != "") {
            mainImage = $(this).val();
        }
    });

    if(mainImage == null || mainImage == '' || mainImage == undefined){
        $.toast('请上传商品logo!');
        return;
    }
     var imgList = new Array();
    $(".imgs_5").each(function (i) {
        if (i == $(".imgs_5").length - 1) {
            return;
        }
        if ($(this).val() != undefined && $(this).val() != "") {
            imgList.push($(this).val());
        }
    });
    if(imgList.length ==0){
        $.toast('请上传详情页轮播图!');
        return;
    }

    $.getJSON('/product/save', 
            {id:id ,
            name:name ,
            mainImage:mainImage,
            imageArray:imgList,
            typeId:typeId ,
            parentTypeId:parentTypeId,
            spec:spec ,
            unit:unit ,
            merchantPrice:merchantPrice ,
            productSatus:productSatus ,
            stock:stock ,
            oldPrice:oldPrice,
            pcContent:pcContent },
        function (data) {
        if(data.success){
            $.toast('保存成功!');
            // $.router.load('/product/list',true);
            window.location.href = '/product/list' ;
        }else {
            $.toast(data.msg);
        }
    });
    
}


//**********************************以下为order 的js方法**********************************




//**********************************以下为merchant 的相关js**********************************
//保存商户
function saveMerchant(state) {
    var id = $('#id_merchantId').val();
    var name = $('#id_name').val();
    var servicePhone = $('#id_servicePhone').val();
    var loginName = $('#id_loginName_name').val();
    var password = $('#id_password').val();
    var password2 = $('#id_password_2').val();
    var idCode = $('#id_code').val();
    var type = $('#type').val();
    var realName = $('#realName').val();
    var classes = $('#classes').val();
    var weChat = $('#weChat').val();
    var teacher = $('#teacher').val();
    var team = $('#team').val();
    var address = $('#address').val();


    if(weChat == null || weChat == ''){
        $.alert('请填写微信号!!');
        return;
    }
    if(teacher == null || teacher == ''){
        $.alert('请填写指导教师!!');
        return;
    }
    if(team == null || team == ''){
        $.alert('请填写团队名称!!');
        return;
    }

    if(idCode == null || idCode == ''){
        $.alert('请填写证件号码!!');
        return;
    }
    if(name == null || name == ''){
        $.alert('请填写商户名称');
        return;
    }

    if(address == null || address == ''){
        $.alert('请填写商户地址');
        return;
    }

    if(loginName == null || loginName == '' || loginName == undefined){
        $.alert('登录名称不能为空!');
        return;
    }

    if(password != null && password.length > 0){
        if(password2 == null || password2 == '' || password2 == undefined){
            $.alert('请确认密码!');
            return;
        }

        if(password != password2){
            $('#id_password').val('');
            $('#id_password_2').val('');
            $.alert('您两次输入的密码不一致,请重新输入!');

            return;
        }
    }
    if(servicePhone == null || servicePhone == ''){
        $.alert('请填写联系电话');
        return;
    }

    var imgList = [];
    $(".imgs").each(function (i) {
        if (i == $(".imgs").length - 1) {
            return;
        }
        if ($(this).val() != undefined && $(this).val() != "") {
            imgList.push($(this).val());
        }
    });
    var imageFile = imgList[0];

    var imgList2 = [];
    $(".imgs2").each(function (j) {
        if (j == $(".imgs2").length - 1) {
            return;
        }
        if ($(this).val() != undefined && $(this).val() != "") {
            imgList2.push($(this).val());
        }
    });
    var idImg = imgList2[0];
    console.log("idCode=="+idCode)
    console.log("state=="+state)
    console.log("type=="+type)
    $.getJSON('/merchant/save', 
        {id:id ,
        name:name ,
        loginName:loginName ,
        password:password ,
        servicePhone:servicePhone ,
        imageFile:imageFile,
            type:type ,
            idCode:idCode,
            state:state,
            idImg:idImg,
            realName:realName,
            classes:classes,
            weChat:weChat,
            teacher:teacher,
            team:team,
            address:address
        },
        function (data) {
            if(data.success){
                $.toast('保存成功!');
               var url = '/'+data.linkId;
                $.router.load(url,true);
            }else {
                $.alert(data.msg);
            }
        });

}


//**********************************以下为user 的相关js**********************************

function getUserOrders() {
    var beganDate = $('#beganDate').val();
    var endDate = $('#endDate').val();
    var userId = $('#id_userId').val();
    // alert('beganDate:' + beganDate + '\n endDate:' + endDate + '\n userId:' + userId);
    $.getJSON('/user/getOrders', {userId:userId , beganDate:beganDate , endDate:endDate}, function (data) {
        console.log(data);
        $('#id_orderNumber').text(data.orderNumber);
        $('#id_totalAmount').text('￥'+data.totalAmount);
        var gettpl = document.getElementById('user_orders_tpl').innerHTML;
        laytpl(gettpl).render(data.orderList, function (html) {
            document.getElementById('idSection').innerHTML = html;
            $("#idSection").scrollTop(0);

        });

    })
}


//**********************************以下为financ 的相关js**********************************

//跳转到提现页面
function canWithDrawal(canWthDrawal) {
    
    if(!canWthDrawal){
        $.toast('您没有提现权限!')
        return;
    }

    $.router.load('/finance/withDrawal');
}

//跳转到提现页面
function isFinancial(canWthDrawal) {

    if(!canWthDrawal){
        $.toast('您没有权限查看财务信息!')
        return;
    }

    $.router.load('/finance/info');
}



//提现
function withDrawal() {
    var amount = $('#id_amount').val();
    var availableAmount = Number($('#id_available_amount').text());
    // alert("amount :"+amount + '\n availableAmount:'+availableAmount);


    if(availableAmount <= 0){
        $.alert('您当前账户余额为 0,无法提现!')
        return;
    }

    if(amount == null || amount == '' || amount == 0){
        $.alert('请输入提现金额!')
        return;
    }

    if(amount < 0){
        $.alert('请输入大于 0 的 提现金额!')
        return;
    }

    if(amount > availableAmount){
        $.alert('提现金额不能大于当前账户余额!')
        return;
    }

    $.toast('走吧,提现去吧!');
}

//获取明细
function getAcciunts(beginDate ,endDate) {

    if(beginDate == null || beginDate == '' || beginDate == undefined){
        $.alert('请选择开始时间');
        return ;
    }
    if(endDate == null || endDate == '' || endDate == undefined){
        $.alert('请选择 结束时间');
        return ;
    }
    
    $.getJSON('/finance/getAccounts',{beginDate:beginDate , endDate:endDate},function (data) {
        console.log(data.billList);
        var gettpl = document.getElementById('account_list_tpl').innerHTML;
        laytpl(gettpl).render(data.billList, function (html) {
            document.getElementById('idSection').innerHTML = html;
            $("#idSection").scrollTop(0);

        });
        document.getElementById('sumMoney').innerHTML = data.sumMoney;

    })
}

//查询
function searchAccounts() {
    var beginDate = $('#id_beganDate').val();
    var endDate = $('#id_endDate').val();
    getAcciunts(beginDate , endDate);
}

//**********************************以下为recommendActivity 的相关js**********************************

//删除
function delRecommend(id) {
   console.log(id);
  $.post('/index/recommend/delete',{id:id},function (data) {
      console.log('data',data);
        if(data.success){
            $.toast('删除成功!');
            var url = '/setUp/index';
            $.router.load(url,true);
        }else {
            $.toast(data.msg);
        }
    })
}
//**********************************以下为登录页面 的相关js**********************************

function forgotPsw() {
    var ua = navigator.userAgent.toLowerCase();
    if(ua.match(/MicroMessenger/i) != "micromessenger") {
        $.alert('请用微信登录再进行操作!');
        return false;
    }
    window.location.href = '/login/forgotPassword';
}

//忘记密码,获取验证码
function forgotPassword() {

    var loginName = $('#id_loginName').val();
    var idCode = $('#id_idCode').val();
    var phone = $('#id_phone').val();
    if(isBlack(loginName) == 1){
        $.alert('请填写登录名!');
        return ;
    }

    if(isBlack(idCode) == 1){
        $.alert('请填写注册证件号码!');
        return ;
    }

    if(isBlack(phone) == 1){
        $.alert('请填写登注册手机号码!');
        return ;
    }

    $.confirm('您确认修改密码?', '系统提示', function () {
        $.getJSON('/login/updatePassWord',{loginName:loginName,idCode:idCode,phone:phone},function (data) {
            if(!data.success){
                $('#id_loginName').val('');
                $('#id_idCode').val('');
                $('#id_phone').val('');
            }
            $.alert(data.msg);
        })
    });

}

//验证码登录
function verificationLogin() {
    var loginName = $('#id_loginName').val();
    var phone = $('#id_phone').val();
    var verificationCode = $('#id_verification_code').val();

    if(isBlack(loginName) == 1){
        $.alert('请填写登录名!');
        return ;
    }

    if(isBlack(verificationCode) == 1){
        $.alert('请填验证码!');
        return ;
    }

    if(isBlack(phone) == 1){
        $.alert('请填写登注册手机号码!');
        return ;
    }

    $.getJSON('/login/verificationLogin',{loginName:loginName,verificationCode:verificationCode,phone:phone},function (data) {
        if(data.success){
            window.location.href= '/merchant/index';
        }else {

            $.alert(data.msg);
        }
    })


}


